﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BrokerBase.Lib.Tool
{
    public class JsonPacker
    {
        public static string EntityToJson(bool success, object entity, string message)
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(entity);

            return string.Format("{0} 'Success': '{1}', 'Data': {2},'Message': '{3}'{4}", "{", success.ToString(), json, message, "}");
        }

        public static T JsonToEntity<T>(string json)
        {
            try
            {

                

                var mStream = new MemoryStream(Encoding.UTF8.GetBytes(json));

                Newtonsoft.Json.Linq.JArray.Load(mStream);

                JsonValue items = JsonArray.Load(mStream);
                T entity = default(T);

                foreach (KeyValuePair<string, JsonValue> item in items)
                {

                    if (item.Key == "Data")
                    {
                        entity = item.Value == null ? default(T) : Newtonsoft.Json.JsonConvert.DeserializeObject<T>(item.Value.ToString());
                    }
                    else if (item.Key == "Message")
                    {
                        if (!string.IsNullOrEmpty(item.Value))
                        {
                            //ReturnMessage message = JsonToMessage(json);
                            Tools.ShowMessage(item.Value, "", false);
                        }
                    }
                }

                return entity;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
